<template>
  <div class="sign-table-panel">
    <div style="justify-content: left; display: flex; margin-bottom: 20px">
      <el-input
        v-model="formInline.drugName"
        placeholder="请输入药品名称"
        style="width: 240px"
        class="filter-item"
        @keyup.enter="handlePageChange(1)"
        @change="handlePageChange(1)"
      />
      <el-select
        v-model="formInline.isSignature"
        @change="handlePageChange(1)"
        placeholder="是否维护"
        style="width: 280px; margin-left: 12px"
      >
        <el-option
          v-for="item in yesOrNoEnum"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        ></el-option>
      </el-select>
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        :height="tableHeight"
        :header-cell-style="{
          background: '#f8f9fa',
          color: '#bbb',
          fontWeight: 600,
          fontSize: '15px',
        }"
        :cell-style="{ fontSize: '16px', color: '#222' }"
      >
        <el-table-column prop="drugName" label="药品名称" />
        <el-table-column prop="drugCategory" label="类型">
          <template #default="scope">
            {{ DrugCategoryEnumText(scope.row.drugCategory) }}
          </template>
        </el-table-column>

        <el-table-column label="手写" width="397">
          <template #default="scope">
            <div class="sign-img-box" v-if="scope.row.signature">
              <img :src="scope.row.signature" class="sign-img" />
            </div>
            <div class="sign-img-box empty" v-else></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="167">
          <template #default="scope">
            <span class="sign-action" @click="onUpload(scope.$index)"
              >上传图片</span
            >
            <span class="sign-action" @click="onHandSign(scope.row)"
              >手写</span
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="shift-page-pagination">
      <Pagination
        style="margin-left: auto"
        :key="formInline.pageSize + 'Pagination' + formInline.pageNo"
        :count="total"
        :page-size="formInline.pageSize"
        :pageNo="formInline.pageNo"
        @onPagechange="handlePageChange"
        @onSizechange="handleSizeChange"
      />
    </div>
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="onFileChange"
    />
    <HandSignBoard v-model="handSignVisible" :rowData="rowData" @confirm="onHandSignConfirm" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { ElTable, ElTableColumn } from 'element-plus';
import { getDrugSignatureList, profileUpdateSignature } from '@/api/individual';
import type { DrugSignatureResponseDataList } from '@/types/individual';
import stores from '@/store';
import { base64Upload } from '@/api/account';

const DrugCategoryEnum = ref<any>(
  stores.useBaseDataStore().getEnumSelect('drugCategoryEnum')
);
const yesOrNoEnum = ref<any>(
  stores.useBaseDataStore().getEnumSelect('yesOrNoEnum')
);
const loading = ref(false);
const total = ref(0);
const formInline = ref<{
  drugName?: string;
  isSignature?: string;
  pageNo: number;
  pageSize: number;
}>({
  drugName: '',
  isSignature: '',
  pageNo: 1,
  pageSize: 10,
});

const tableData = ref<DrugSignatureResponseDataList[]>([]);
const getDrugSignatureListApi = () => {
  let data = {
    drugName: formInline.value.drugName,
    isSignature: formInline.value.isSignature,
    pageNo: formInline.value.pageNo,
    pageSize: formInline.value.pageSize,
  };
  loading.value = true;
  getDrugSignatureList(data).then((res) => {
    tableData.value = res.data.list;
    total.value = res.data.totalCount;
    loading.value = false;
  });
};

const handlePageChange = (page: number) => {
  formInline.value.pageNo = page;
  getDrugSignatureListApi();
};
const handleSizeChange = (size: number) => {
  formInline.value.pageSize = size;
  formInline.value.pageNo = 1;
  getDrugSignatureListApi();
};
getDrugSignatureListApi();

// 表格高度（固定表头，内容滚动）
const tableHeight = ref<number>(window.innerHeight - 250);
const updateTableHeight = () => {
  tableHeight.value = window.innerHeight - 250;
};
onMounted(() => {
  window.addEventListener('resize', updateTableHeight);
});
onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight);
});

const DrugCategoryEnumText = (val: string) => {
  return DrugCategoryEnum.value.find((item: any) => item.value === val)?.text;
};

const fileInput = ref<HTMLInputElement | null>(null);
const uploadIdx = ref<number>(0);
const handSignVisible = ref(false);
const handSignIdx = ref<number>(0);

const onUpload = (idx: number) => {
  uploadIdx.value = idx;
  fileInput.value?.click();
};
const onFileChange = (e: Event) => {
  const files = (e.target as HTMLInputElement).files;
  if (files && files[0] && uploadIdx.value !== null) {
    const reader = new FileReader();
    reader.onload = (ev) => {
      let drugId: any = 0;
      if (
        tableData.value.length > uploadIdx.value &&
        tableData.value[uploadIdx.value]
      ) {
        drugId = tableData.value[uploadIdx.value]?.drugId;
      }
      base64Upload({
        baseStr: ev.target?.result as string,
        isCompress: 'true',
      }).then((res) => {
        if (res.code === '200') {
          profileUpdateSignature({
            drugId: drugId,
            signature: res.data,
          }).then((ress) => {
            if (ress.code === '200') {
              handlePageChange(1);
              ElMessage.success(ress.msg);
            } else {
              // ElMessage.success(ress.msg);
            }
          });
        } else {
          // ElMessage.success(res.msg);
        }
      });
    };
    reader.readAsDataURL(files[0]);
  }
};
const rowData = ref<any>(null);
const onHandSign = (row:any) => {
  // handSignIdx.value = idx;
  rowData.value = row;
  handSignVisible.value = true;
};
const onHandSignConfirm = (img: string) => {
  base64Upload({
    baseStr: img,
    isCompress: 'true',
  }).then((res) => {
    if (res.code === '200') {
      let drugId: any = 0;
      drugId = rowData.value?.drugId;
      profileUpdateSignature({
        drugId: drugId,
        signature: res.data,
      }).then((ress) => {
        if (ress.code === '200') {

          handlePageChange(1);
          ElMessage.success(ress.msg);
          if(ress.data != null){
            onHandSign(ress.data)
          }

        } else {
          // ElMessage.success(ress.msg);
        }
      });
    } else {
      // ElMessage.success(res.msg);
    }
  });
};
</script>

<style scoped>
.sign-table-panel {
  background: #fff;
  border-radius: 8px;
  min-width: 900px;
  padding: 0 24px 0px 24px;
}
.sign-table-header {
  display: flex;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
  font-size: 15px;
  color: #bbb;
  font-weight: 600;
  padding: 0 32px;
  height: 48px;
  align-items: center;
}
.sign-table-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  min-height: 80px;
  padding: 0 32px;
}
.cell {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #222;
}
.cell.name {
  flex: 0 0 180px;
}
.cell.type {
  flex: 0 0 120px;
}
.cell.sign {
  flex: 0 0 320px;
  justify-content: center;
}
.cell.action {
  flex: 1;
  justify-content: flex-start;
  color: #18b3ab;
  font-size: 15px;
  gap: 18px;
}
.sign-img-box {
  width: 300px;
  height: 80px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: rgba(238, 238, 238, 1);
}
.sign-img-box.empty {
}
.sign-img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
.sign-action {
  color: #18b3ab;
  cursor: pointer;
  margin-right: 18px;
  transition: color 0.2s;
}
.sign-action:last-child {
  margin-right: 0;
}
.sign-action:hover {
  color: #13a39a;
}
.shift-page-pagination {
  margin-top: 10px; 
}

</style>
